package com.le.tester.book.concurrentjavafight.l_14;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * createTime：2024/5/25 16:33
 * description：使用AbstractQueuedSynchronize实现二元闭锁
 */
public class OneShotLatch {

    private final Sync sync = new Sync();

    public void single() {
        sync.releaseShared(0);
    }

    public void await() {
        sync.acquiredSharedInterruptibly(0);
    }

    private class Sync extends AbstractQueuedSynchronizer {
        protected int tryAcquireShared(int ignored) {
            return (getState() == 1) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int ignored) {
            //打开
            setState(1);
            //可以获取
            return true;
        }

        public void acquiredSharedInterruptibly(int i) {
            setState(i);
        }
    }
}
